<template>
  <div class="bg">
    <div class="login-box">
      <h1>叩丁狼商品管理系统</h1>
      <el-form ref="ruleFormRef" :model="loginData" :rules="loginRules" label-width="0">
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="loginData.username" :prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入用密码" v-model="loginData.password" :prefix-icon="Lock" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue';
import { loginApi } from '@/api';
import { useRouter } from 'vue-router';
const router = useRouter()

const ruleFormRef = ref<FormInstance>()

const loginData = reactive({
  username: '',
  password: ''
})

// 表单校验规则要生效，有一个条件： 1. 表单数据对象的属性名和rules对象的属性名一致 2. form-item身上有prop属性，值也一致
const loginRules = reactive<FormRules>({
  username: [
    // 每个表单的规则都是可以写多个的
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ]
})

const submit = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 提交表单 ， 发送请求
      loginApi(loginData).then(res => {
        if (res.code === 200) {
          // 登录成功
          // 存储token
          localStorage.setItem('token', res.data.tokenHead + res.data.token)
          // 提示用户 - 一定要记得在main.ts引入样式
          ElMessage.success('登录成功')
          // 跳转到首页
          router.push('/index')
        }
      })
    } else {
      return false;
    }
  })
}

</script>

<style scoped lang="less">
.bg {
  background-color: #2d3a4b;
  height: 100vh;
  width: 100vw;

  .login-box {
    width: 400px;
    margin: 0 auto;
    padding-top: 300px;

    h1 {
      text-align: center;
      font-weight: 400;
      color: #fff;
      padding: 20px 0;
    }

    .el-button--primary {
      width: 100%;
    }
  }
}
</style>